"""
闲鱼API模块 (原 XianyuApis.py)
提供闲鱼平台的基础API调用功能
"""

import json
import time
import requests
from loguru import logger

from utils.xianyu_utils import generate_sign, trans_cookies, generate_device_id


class XianyuAPI:
    """闲鱼API客户端"""
    
    def __init__(self):
        self.url = 'https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.login.token/1.0/'

    def get_token(self, cookies, device_id):
        """获取闲鱼WebSocket连接所需的token"""
        headers = {
            'accept': 'application/json',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'no-cache',
            'origin': 'https://www.goofish.com',
            'pragma': 'no-cache',
            'priority': 'u=1, i',
            'referer': 'https://www.goofish.com/',
            'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
        }
        
        params = {
            'jsv': '2.7.2',
            'appKey': '34839810',
            't': str(int(time.time()) * 1000),
            'sign': '',
            'v': '1.0',
            'type': 'originaljson',
            'accountSite': 'xianyu',
            'dataType': 'json',
            'timeout': '20000',
            'api': 'mtop.taobao.idlemessage.pc.login.token',
            'sessionOption': 'AutoLoginOnly',
            'spm_cnt': 'a21ybx.im.0.0',
        }
        
        data_val = '{"appKey":"444e9908a51d1cb236a27862abc769c9","deviceId":"' + device_id + '"}'
        data = {'data': data_val}
        
        token = cookies['_m_h5_tk'].split('_')[0]
        
        try:
            logger.debug(f"签名输入: t={params['t']}, token={token[:10]}..., deviceId={device_id}")
        except Exception:
            pass

        import hashlib
        msg = f"{token}&{params['t']}&{params['appKey']}&{data_val}"
        sign_py = hashlib.md5(msg.encode('utf-8')).hexdigest()
        sign_js = None
        
        try:
            sign_js = generate_sign(params['t'], token, data_val)
        except Exception as e:
            logger.debug(f"JS签名计算失败，使用Python签名: {e}")
            
        if sign_js and sign_js != sign_py:
            logger.debug(f"JS签名与Python签名不一致: js={sign_js} py={sign_py}")
            
        params['sign'] = sign_py
        
        response = requests.post(
            'https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.login.token/1.0/', 
            params=params, 
            cookies=cookies, 
            headers=headers, 
            data=data
        )
        
        try:
            logger.debug(f"获取token响应状态码: {response.status_code}")
            logger.debug(f"获取token原始响应长度: {len(response.text)}")
        except Exception:
            pass
            
        res_json = response.json()
        
        try:
            if 'ret' in res_json:
                logger.debug(f"获取token ret: {res_json['ret']}")
            if isinstance(res_json.get('data'), dict):
                logger.debug(f"获取token data字段keys: {list(res_json['data'].keys())}")
            logger.debug(f"data.accessToken存在: {bool(isinstance(res_json.get('data'), dict) and 'accessToken' in res_json['data'])}")
        except Exception:
            pass
            
        return res_json

